from service.data import BusinessErrorCode, BusinessErrorMes
from service.handle_format import get_public_private_attribute, get_handle_to_proxy, get_company_info, request_handle_proxy
from service.common import insert_data, find_data, update_data, delete_data, get_condition
from pao_python.pao.data import process_db, dataframe_to_list, data_to_string_date, JsonRpc2Error, DataProcess
import json
import requests
import pymongo
import pandas as pd
from pao_python.pao.service.security.security_service import LoginService
import uuid
import time
import qrcode
from PIL import Image, ImageDraw, ImageFont
import os
from service.img_text import ImgText


class HandleManageMent(DataProcess):

    # 新增/编辑标识
    # index为标识的排序号，如品类标识的类目属性index为2xx
    def update_company(self, handle_data, handle_type, company_mes={}):
        res = False
        def process_func(db):
            nonlocal res
            has_handle = find_data(db, 'IDMIS_Handle', {
                                   'handle_code': handle_data['handle_code']})
            insert_company_result = True  # 若标识为企业标识
            company_info = {}
            # 数据格式化处理,分为'public'字段标识表记录,和'private'字段类目属性表字段
            # 模拟user_id
            attribute_dict = get_public_private_attribute(
                handle_data, handle_type, db)
            if handle_type == 'company':
                company_info = get_company_info(company_mes)
            # 新建标识

            if attribute_dict['operate_type']:
                if len(has_handle) > 0:
                    raise JsonRpc2Error(
                        BusinessErrorCode.HANDLE_EXIST, BusinessErrorMes.HANDLE_EXIST)
                if handle_type == 'company':
                    insert_company_result = insert_data(
                        db, 'IDMIS_Company', company_info)
                insert_public_result = insert_data(
                    db, 'IDMIS_Handle', attribute_dict['public'])  # 创建标识记录
                insert_private_result = insert_data(
                    db, 'IDMIS_Attribute', attribute_dict['private'])  # 创建类目属性记录
                # 创建关联标识
                # if len(attribute_dict['reference_cols']) > 0:
                #     for x in attribute_dict['reference_cols']:
                #         insert_reference_result = insert_data(
                #             db, 'IDMIS_Handle_Reference', x)
                # else:
                # insert_reference_result = True
                # 本地保存成功，则保存到proxy
                if insert_public_result and insert_private_result and insert_company_result:
                    # 获取要存到代理服务器的类目属性
                    attribute_data = attribute_dict['private']['attribute_data']
                    proxy_handle_data = get_handle_to_proxy(attribute_data)  # 转换成代理服务器的标识值
                    # 在代理服务器(proxy)创建标识
                    try:
                        headers = self.__xingtongyuan_login(
                            handle_data['user_id'])
                        create_handle_porxy = requests.post(
                            'http://idisif.gdsinsing.com:8080/'+handle_data['handle_code'], data=json.dumps(proxy_handle_data), headers=headers).json()  # 查询
                        print(create_handle_porxy, '创建解析结果')
                        if create_handle_porxy['responseCode'] == 1:
                            res = True
                        else:  # 若proxy新增失败，则删除本地数据库新建的标识和类目属性
                            del_handle = delete_data(db, 'IDMIS_Handle', {
                                                     'id': attribute_dict['public']['id']})
                            del_attribute = delete_data(db, 'IDMIS_Attribute', {
                                                        'handle_id': attribute_dict['public']['id']})
                            # if len(attribute_dict['reference_cols']) > 0:
                            #     for x in attribute_dict['reference_cols']:
                            #         delete_data(db, 'IDMIS_Handle_Reference', {
                            #                     'handle_id': x['handle_id']})
                            if handle_type == 'company':
                                delete_data(db, 'IDMIS_Company', {
                                            'id': company_info['id']})
                            raise JsonRpc2Error(
                                create_handle_porxy['responseCode'], create_handle_porxy['msg'])
                    except Exception as e:
                        del_handle = delete_data(db, 'IDMIS_Handle', {
                                                 'id': attribute_dict['public']['id']})
                        del_attribute = delete_data(db, 'IDMIS_Attribute', {
                                                    'handle_id': attribute_dict['public']['id']})
                        # if attribute_dict['reference_cols'] != []:
                        #     for x in attribute_dict['reference_cols']:
                        #         del_refer_handle = delete_data(db, 'IDMIS_Handle_Reference', {
                        #                                        'handle_id': x['handle_id']})
                        if handle_type == 'company':
                            delete_data(db, 'IDMIS_Company', {
                                        'id': company_info['id']})
                        raise JsonRpc2Error(
                            BusinessErrorCode.UNUSUAL, BusinessErrorMes.UNUSUAL)
                else:
                    pass

            # #更新标识
            else:
                update_company_result = True
                # 备份数据
                backup_handle = find_data(
                    db, 'IDMIS_Handle', {'id': handle_data['id']})[0]
                backup_attribute = find_data(db, 'IDMIS_Attribute', {
                                             'handle_id': handle_data['id']})[0]
                # 品类
                # reference_len = db['IDMIS_Handle_Reference'].find(
                #     {'handle_id': handle_data['handle_code']}).count()

                # 若为企业标识，备份企业信息
                if handle_type == 'company':
                    backup_company = find_data(db, 'IDMIS_Company', {
                                               'id': company_info['id']})[0]
                    update_company_result = update_data(
                        db, 'IDMIS_Company', company_info, {'id': company_info['id']})

                update_public_result = update_data(
                    db, 'IDMIS_Handle', attribute_dict['public'], {'id': handle_data['id']})
                update_private_result = update_data(
                    db, 'IDMIS_Attribute', attribute_dict['private'], {'handle_id': handle_data['id']})
                # 单品标识，更新关联表中与品类的关联信息
                # if reference_len > 1:
                #     backup_reference = find_data(db, 'IDMIS_Handle_Reference', {
                #                                  'handle_id': handle_data['handle_code'], 'ref_type': 'category_handle_code'})
                #     backup_reference_company = find_data(db,'IDMIS_Handle_Reference',{'handle_id':handle_data['handle_code'],'ref_type':'company_handle_code'})
                #     if len(attribute_dict['reference_cols']) > 0:
                #         for x in attribute_dict['reference_cols']:
                #             if x['ref_type'] == 'category_handle_code':
                #                 update_reference_result = update_data(db, 'IDMIS_Handle_Reference', x, {'handle_id': handle_data['handle_code'], 'ref_type': 'category_handle_code'})
                #             if x['ref_type'] == 'company_handle_code':
                #                 update_reference_company_result = update_data(db,'IDMIS_Handle_Reference',x,{'handle_id':handle_data['handle_code'],'ref_type':'company_handle_code'})
                if update_public_result and update_private_result and update_company_result:
                    # res = True
                    # 获取要存到代理服务器的类目属性
                    attribute_data = attribute_dict['private']['attribute_data']
                    proxy_handle_data = get_handle_to_proxy(
                        attribute_data)  # 转换成代理服务器的标识值
                    # 更新成功,则更新到代理服务器,
                    try:
                        print(backup_handle,'backup_handle>>>')
                        headers = self.__xingtongyuan_login(
                            backup_handle['user_id'])
                        proxy_handle_data['action'] = "modifyHandleValue"
                        update_handle_porxy = requests.put('http://idisif.gdsinsing.com:8080/'+handle_data['handle_code'],data=json.dumps(proxy_handle_data),headers=headers).json() #查询
                        print(update_handle_porxy,'更新解析结果')
                        if update_handle_porxy['responseCode'] == 1:
                            res = True
                        else:#若失败，则恢复数据
                            update_data(db,'IDMIS_Handle',backup_handle,{'id':handle_data['id']})
                            update_data(db,'IDMIS_Attribute',backup_attribute,{'handle_id':handle_data['id']})
                            # if reference_len > 1:
                            #     if len(backup_reference) > 1:
                            #         update_data(db,'IDMIS_Handle_Reference',backup_reference,{'handle_id':handle_data['handle_code']})
                            #     if len(backup_reference_company) > 1:
                            #         update_data(db,'IDMIS_Handle_Reference',backup_reference_company,{'handle_id':handle_data['handle_code']})
                            if handle_type == 'company':
                                update_data(db,'IDMIS_Company',backup_company,{'id':company_info['id']})
                    except Exception as e:
                        update_data(db,'IDMIS_Handle',backup_handle,{'id':handle_data['id']})
                        update_data(db,'IDMIS_Attribute',backup_attribute,{'handle_id':handle_data['id']})
                        # if reference_len > 1:
                        #     if len(backup_reference) > 1:
                        #             update_data(db,'IDMIS_Handle_Reference',backup_reference,{'handle_id':handle_data['handle_code']})
                        #     if len(backup_reference_company) > 1:
                        #         update_data(db,'IDMIS_Handle_Reference',backup_reference_company,{'handle_id':handle_data['handle_code']})
                        if handle_type == 'company':
                            update_data(db,'IDMIS_Company',backup_company,{'id':company_info['id']})

                else:
                    update_data(db, 'IDMIS_Handle', backup_handle,
                                {'id': handle_data['id']})
                    update_data(db, 'IDMIS_Attribute', backup_attribute, {
                                'handle_id': handle_data['id']})
                    if handle_type == 'IDMIS_Company':
                        update_data(db, 'IDMIS_Company', company_info, {
                                    'id': company_info['id']})
        process_db(self.db_addr, self.db_port, 'IDMIS', process_func)
        return res

    def insert_preview(self, handle_data, handle_type):
        res = {'attribute': [], 'handle_code': handle_data['handle_code'],
               'handle_name': handle_data['handle_name']}
        # REFERNCE_KEY = ['company_handle_code', 'category_handle_code']
        REFERNCE_KEY = ['parent_id']
        def process_func(db):
            nonlocal res
            attribute_dict = get_public_private_attribute(
                handle_data, handle_type, db)
            # 获取要存到代理服务器的类目属性
            attribute_data = attribute_dict['private']['attribute_data']
            proxy_handle_data = get_handle_to_proxy(
                attribute_data)['value']  # 转换成代理服务器的标识值
            if len(proxy_handle_data) > 0:
                for x in proxy_handle_data:
                    attribute = json.loads(x['data']['value'])
                    res['attribute'].append(attribute)
                    # 查询父级是否有企业标识信息
                    if attribute['sign_key'] in REFERNCE_KEY and not attribute['sign_value'].strip()=='':
                        parent_id = attribute['sign_value']
                        isEnd = True
                        while isEnd:
                            handle_mes = find_data(db, 'IDMIS_Handle', {'id': parent_id})
                            if len(handle_mes) > 0 and handle_mes[0]['handle_type'] == 'classify':
                                if handle_mes[0]['parent_id']:
                                    parent_id = handle_mes[0]['parent_id']
                                else:
                                    isEnd = False
                            elif len(handle_mes) > 0 and handle_mes[0]['handle_type'] == 'company':
                                res['attribute'] = res['attribute'] + request_handle_proxy(handle_mes[0]['handle_code'])
                                isEnd = False
                            else:
                                isEnd = False
                    # if attribute['sign_key'] in REFERNCE_KEY and not attribute['sign_value'].strip()=='':
                    #     res['attribute'] = res['attribute'] + \
                    #         request_handle_proxy(attribute['sign_value'])
            # 数据去重
            pd_attribute = pd.DataFrame(
                res['attribute']).drop_duplicates(['index'])
            get_arttribute = dataframe_to_list(pd_attribute)
            res['attribute'] = get_arttribute
        process_db(self.db_addr, self.db_port, 'IDMIS', process_func)
        return res

    # 查询标识列表
    def get_company_list(self, condition, page, count, industry_type='product_type'):
        res = {'result': []}

        def process_func(db):
            nonlocal res
            cols = db['IDMIS_Handle']
            new_condition = get_condition(condition)
            if page and count:
                data_list = list(cols.find(new_condition)[
                                 (page-1)*count:(page-1)*count+count])
            else:
                data_list = list(cols.find(new_condition)[:])
            res['total'] = cols.find(new_condition).count()
            if len(data_list) > 0:
                for x in data_list:
                    otherStyleTime = data_to_string_date(x['create_date'])
                    x['create_date'] = otherStyleTime
                pd_equit = pd.DataFrame(data_list).drop(['_id'], axis=1)
                res['result'] = dataframe_to_list(pd_equit)

        process_db(self.db_addr, self.db_port, 'IDMIS', process_func)
        return res

    # 查询关联列表
    def get_reference_handle_list(self, product_type, condition_dict, page, count, handle_type=None):
        res = {'result': []}
        condition = get_condition(condition_dict)

        def process_func(db):
            nonlocal res
            id_condition = {}
            handle_info = find_data(db, 'IDMIS_Handle', {
                                    'id': condition['id']})[0]
            condition['handle_code'] = handle_info['handle_code']
            # 单品则查询的是父级品类
            if handle_type == 'single_product':
                id_condition = {'handle_id': condition['handle_code']}
                id_result_key = 'ref_handle_id'
            else:
                id_condition = {'ref_handle_id': condition['handle_code']}
                id_result_key = 'handle_id'
            # 获取父级所关联的所有handle_id
            ref_handle_list = find_data(
                db, 'IDMIS_Handle_Reference', id_condition)
            if len(ref_handle_list) > 0:
                handle_list = pd.DataFrame(ref_handle_list)[
                    id_result_key].to_list()
                condition['handle_code'] = {'$in': handle_list}
                del condition['id']
                # 总数
                res['total'] = db['IDMIS_Handle'].find(condition).count()
                if page and count:
                    get_handle_list = list(db['IDMIS_Handle'].find(condition)[
                                           (page-1)*count:(page-1)*count+count])
                else:
                    get_handle_list = list(
                        db['IDMIS_Handle'].find(condition)[:])
                if len(get_handle_list) > 0:
                    for x in get_handle_list:
                        otherStyleTime = data_to_string_date(x['create_date'])
                        x['create_date'] = otherStyleTime
                    pd_list = pd.DataFrame(
                        get_handle_list).drop(['_id'], axis=1)
                    res['result'] = dataframe_to_list(pd_list)

        process_db(self.db_addr, self.db_port, 'IDMIS', process_func)
        return res

    # 获取企业信息
    def get_company(self, user_id):

        res = {}

        def process_func(db):
            nonlocal res
            company_mes = find_data(db, 'IDMIS_Company', {'user_id': user_id})
            if len(company_mes) > 0:
                res = dataframe_to_list(pd.DataFrame(
                    company_mes).drop(['_id'], axis=1))[0]
                # res = {
                #     'id':company_mes[0]['id'],
                #     'user_id':company_mes[0]['user_id'],
                #     'manager_name':company_mes[0]['manager_name'],
                #     'license':company_mes[0]['license'],
                #     'contact':
                #     'id_picture':company_mes[0]['id_picture']
                # }
        process_db(self.db_addr, self.db_port, 'IDMIS', process_func)
        return res

    # 删除标识
    def delete_handle(self, handle_id, user_id):
        res = False

        def process_func(db):
            nonlocal res
            # 缓存将删除的数据，若proxy删除失败，则需恢复本地数据
            handle_list = find_data(db, 'IDMIS_Handle', {
                                    'id': {'$in': handle_id}})
            handle_code_list = list(pd.DataFrame(
                handle_list)['handle_code'].values)
            arttribute_list = find_data(db, 'IDMIS_Attribute', {
                                        'handle_id': {'$in': handle_id}})
            # handle_reference_list = find_data(db, 'IDMIS_Handle_Reference', {
            #                                   'handle_id': {'$in': handle_code_list}})
            # 若是企业标识，还需删除企业信息
            # 删除
            del_handle = delete_data(db, 'IDMIS_Handle', {
                                     'id': {'$in': handle_id}})
            del_attribute = delete_data(db, 'IDMIS_Attribute', {
                                        'handle_id': {'$in': handle_id}})
            # del_handle_reference = delete_data(db, 'IDMIS_Handle_Reference', {
            #                                    'handle_id': {'$in': handle_code_list}})
            if del_handle and del_attribute:
                headers = self.__xingtongyuan_login(user_id)
                for x in handle_list:
                    try:
                        del_handle_porxy = requests.delete(
                            'http://idisif.gdsinsing.com:8080/'+x['handle_code'], headers=headers).json()  # 查询
                        if del_handle_porxy['responseCode'] == 1:
                            res = True
                        else:  # 恢复数据
                            insert_data(db, 'IDMIS_Handle', handle_list[0])
                            insert_data(db, 'IDMIS_Attribute',
                                        arttribute_list[0])
                            # insert_data(db, 'IDMIS_Handle_Reference',
                            #             handle_reference_list[0])
                            res = False
                    except Exception as e:
                        insert_data(db, 'IDMIS_Handle', handle_list[0])
                        insert_data(db, 'IDMIS_Attribute', arttribute_list[0])
                        # insert_data(db, 'IDMIS_Handle_Reference',
                        #             handle_reference_list[0])
                        res = False
        process_db(self.db_addr, self.db_port, 'IDMIS', process_func)
        return res

    def is_allow_delete(self, handle_id):
        '''查询是否被关联'''
        res = False

        def process_func(db):
            nonlocal res
            handle_list = find_data(db, 'IDMIS_Handle', {
                                    'id': {'$in': handle_id}})
            handle_code_list = list(pd.DataFrame(
                handle_list)['handle_code'].values)
            handle_reference_list = find_data(db, 'IDMIS_Handle_Reference', {
                                              'ref_handle_id': {'$in': handle_code_list}})
            if len(handle_reference_list) < 1:
                res = True
        process_db(self.db_addr, self.db_port, 'IDMIS', process_func)
        return res
    # 获取标识信息

    def get_sign_mes(self, handle_id, no_type='industry_type'):
        res = {}

        def process_func(db):
            nonlocal res
            handle_mes = find_data(db, 'IDMIS_Handle', {'id': handle_id})
            # proxy类目属性
            if len(handle_mes) > 0:
                handle_code = handle_mes[0]['handle_code']
                if 'create_date' in handle_mes[0].keys():
                    date = data_to_string_date(handle_mes[0]['create_date'])
                    handle_mes[0]['create_date'] = date
                data_dict = requests.get(
                    'http://idisif.gdsinsing.com:8080/'+handle_code).json()
                if data_dict['responseCode'] == 1 and len(data_dict["value"]) > 0:
                    res = dataframe_to_list(pd.DataFrame(
                        handle_mes).drop(['_id'], axis=1))[0]
                    for sinle_dict in data_dict["value"]:
                        attribute = json.loads(sinle_dict["data"]["value"])
                        res[attribute['sign_key']] = attribute['sign_value']
        process_db(self.db_addr, self.db_port, 'IDMIS', process_func)
        return res

    # 获取当前用户企业标识
    def get_current_user_company_sign(self, user_id):
        res = {}

        def process_func(db):
            nonlocal res
            print('begin_handle_mes')
            handle_mes = find_data(db, 'IDMIS_Handle', {'handle_type': 'company', 'user_id': user_id})
            if len(handle_mes) > 0:
                print(handle_mes,'handle_mes')
                res = {
                    'id': handle_mes[0]['id'],
                    'user_id': handle_mes[0]['user_id'],
                    'handle_code': handle_mes[0]['handle_code'],
                    'handle_name': handle_mes[0]['handle_name'],
                    'handle_type': handle_mes[0]['handle_type'],
                    # 'rc_code':handle_mes['rc_code'],
                    'industry_type': handle_mes[0]['industry_type'],
                    'create_date': handle_mes[0]['create_date'],
                    'modify_date': handle_mes[0]['modify_date']
                }
                attribute_mes = find_data(db, 'IDMIS_Attribute', {
                                        'handle_id': handle_mes[0]['id']})
                if len(attribute_mes) > 0:
                    datas = attribute_mes[0]['attribute_data']
                    for data in datas:
                        sign_name = ''
                        sign_value = ''
                        for key, value in data.items():
                            if key == 'sign_key':
                                sign_name = value
                            if key == 'sign_value':
                                sign_value = value
                        if sign_name != '' and sign_value != '':
                            res[sign_name] = sign_value
        process_db(self.db_addr, self.db_port, 'IDMIS', process_func)
        print(res,'res')
        return res

    def is_insert(self, user_id):
        ''' 判断是否新建标识
            Args:
                user_id     用户id
        '''
        res = {}

        def process_func(db):
            nonlocal res
            handle_mes = find_data(db, 'IDMIS_Handle', {
                                   'handle_type': 'company', 'user_id': user_id})
            if len(handle_mes) > 0:
                handle_id = handle_mes[0]['id']
                res = self.get_sign_mes(handle_id)
        process_db(self.db_addr, self.db_port, self.db_name, process_func)
        return res

    def __xingtongyuan_login(self, user_id):
        ''' 信通院登录
            描述：操作标识之前需要登录信通院账户，获取taken
            Args:   user_id     用户id
            Return:
                    responseCode    响应码
                    msg     信息
                    token   登录成功token
        '''
        res = None

        def process_func(db):
            nonlocal res
            collection = db['IDMIS_User']
            user_list = list(collection.find({'id': user_id})[:])
            if len(user_list) > 0:
                try:
                    login_info = {
                        'user': user_list[0]['caict_account'], 'passwd': user_list[0]['caict_pw']}
                    login_result = requests.post(
                        'http://idisif.gdsinsing.com:8080/login', data=json.dumps(login_info)).json()
                    print(login_result, '登录结果')
                    if login_result['responseCode'] == 1:
                        res = {'Authorization': 'Bearer ' +
                               login_result['token']}
                    else:
                        raise JsonRpc2Error(
                            BusinessErrorCode.LOGIN_FAIL, BusinessErrorMes.LOGIN_FAIL)
                except:
                    raise JsonRpc2Error(
                        BusinessErrorCode.LOGIN_FAIL, BusinessErrorMes.LOGIN_FAIL)
        process_db(self.db_addr, self.db_port, self.db_name, process_func)
        return res

    def create_qr_code(self, web_path, upload_file, handle_code, use_logo, logo, user_id):
        res = {}

        def process_func(db):
            nonlocal res
            logo_picture = ''
            # 如果传入参数存在use_logo则直接用传入的Logo(如果logo为空也使用，场景：企业标识由有Logo更改为没有Logo),否则取企业标识信息中的qr_logo字段
            if use_logo:
                logo_picture = logo
            else:
                handle_mes = find_data(db, 'IDMIS_Handle', {
                                       'handle_type': 'company', 'user_id': user_id})
                if len(handle_mes) > 0:
                    if 'qr_code_logo_picture' in handle_mes[0]:
                        # 默认取第一张图片
                        logo_picture = handle_mes[0]['qr_code_logo_picture'][0]
            res = self.qr_code(web_path, upload_file,
                               handle_code, logo_picture)
        process_db(self.db_addr, self.db_port, 'IDMIS', process_func)
        return res

    def qr_code(self, web_path, upload_file, handle_code, logo):
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=2,
        )
        # 添加数据
        qr.add_data("http://192.168.97.135:3000/sign-analysis?key="+handle_code)
        # 填充数据
        qr.make(fit=True)
        # 生成图片
        img = qr.make_image(fill_color="black", back_color="white")
        img = img.convert("RGBA")  # CMYK
        # 获取图片的宽高
        img_w, img_h = img.size
        # 添加文字
        font = ImageFont.truetype("micross.ttf", 20)
        n = ImgText(handle_code, img, int(img_w * 0.8), font)
        ''' 获取文字换行后高度 '''
        note_height = n.get_note_height()
        # line_height = n.get_line_height()
        line_count = n.get_line_count()
        char_width = n.get_char_width()
        print(char_width)
        # new_img_w = img_w+note_height+line_height
        ''' 根据最终高度绘制新的图片 '''
        new_img_h = img_h+note_height
        note_img = Image.new(
            "RGBA", (img_w, new_img_h), (255, 255, 255, 255))
        ''' 把二维码和文字放入其中 '''
        note_img.paste(img, (0, 0))
        n = ImgText(handle_code, note_img,
                    int(img_w * 0.8), font, (0, 0, 0, 255))
        # text_w = int(img_w / 10)
        text_w = int((img_w - int(img_w * 0.8)) / 2)
        if line_count == 1:
            text_w = int((img_w - char_width) / 2)
        img = n.draw_text(text_w, img_h-10)

        # 添加logo
        if logo:
            icon = Image.open((web_path+'/'+logo).replace('\\', '/'))
            # factor = 4
            # size_w = int(img_w / factor)
            # size_h = int(img_h / factor)
            # icon_w, icon_h = icon.size
            # if icon_w > size_w:
            #     icon_w = size_w
            # if icon_h > size_h:
            #     icon_h = size_h
            # 重新设置logo的尺寸
            icon = icon.resize((120, 120), Image.ANTIALIAS)
            w = int((img_w - 120) / 2)
            h = int((img_h - 120) / 2)
            img.paste(icon, (w, h), icon)
        # 显示图片
        # plt.imshow(img)
        # plt.show()
        # time_id = str(int(time.time()))
        upload_path = upload_file + '\\'+handle_code  # 以标识码命名文件
        file_path = (web_path+'/'+upload_path).replace('\\', '/')
        if not os.path.exists(file_path):  # 不存在改目录则会自动创建
            os.makedirs(file_path)
        img.save(os.path.join(file_path, handle_code.replace(
            '/', '-')+'.png').replace('\\', '/'))
        # 拼接文件url地址
        result = {'code': 200, 'desc': '上传成功', }
        result['url'] = os.path.join(upload_path, handle_code.replace(
            '/', '-')+'.png').replace('\\', '/')
        return result

    def get_single_category_list(self,user_id):
        res = {'result':[]}
        def process_func(db):
            nonlocal res
            handle_mes = find_data(db,'IDMIS_Handle',{'handle_type':'category','user_id':user_id})
            if len(handle_mes)>0:
                pd_list = pd.DataFrame(handle_mes).drop(['_id'],axis=1)
                res['result'] = dataframe_to_list(pd_list)
        process_db(self.db_addr,self.db_port,self.db_name, process_func)
        return res